<template>
  <div>
    <!-- 添加或修改系统应用对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body v-dialogDrag>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="form.appName" placeholder="请输入应用名称" maxlength="20" show-word-limit class="limit" />
        </el-form-item>
        <el-form-item prop="appCode">
          <span slot="label">
            <span class="span-box">
              <el-tooltip class="item" effect="dark" :content="`应用的唯一标识，一经确定后不可修改。`" placement="top-start">
                <i class="el-icon-question" />
              </el-tooltip>
              应用编码
            </span>
          </span>
          <el-input v-model="form.appCode" placeholder="请输入编码" :disabled="form.appId !== null" maxlength="20" show-word-limit class="limit" />
        </el-form-item>
        <el-form-item label="应用类型" prop="appType">
          <span slot="label">
            <span class="span-box">
              <el-tooltip class="item" effect="dark" :content="`应用类型是为平台门户首页展示做的分类。`" placement="top-start">
                <i class="el-icon-question" />
              </el-tooltip>
              应用类型
            </span>
          </span>
          <el-select v-model="form.appType" placeholder="请选择应用类型" style="width:100%;">
            <el-option
              v-for="dict in appTypeSelect"
              :key="dict.id"
              :label="dict.typeName"
              :value="parseInt(dict.id)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="应用来源" prop="appSource">
          <el-radio-group v-model="form.appSource" @change="changeAppSource">
            <el-radio
              v-for="dict in appSourceSelect"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="是否打开新页签" prop="openNewTag">
          <el-radio-group v-model="form.openNewTag" :disabled="form.appSource == 2">
            <el-radio
              v-for="dict in openNewTagSelect"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.appSource ==2 " label="是否需要单点集成" prop="isSingleIntegration">
          <el-radio-group v-model="form.isSingleIntegration">
            <el-radio
              v-for="dict in openNewTagSelect"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item prop="isBaseApp">
          <span slot="label">
            <span class="span-box">
              <el-tooltip class="item" effect="dark" :content="`基础应用不可删除`" placement="top-start">
                <i class="el-icon-question" />
              </el-tooltip>
              是否基础应用
            </span>
          </span>
          <el-radio-group v-model="form.isBaseApp">
            <el-radio
              v-for="dict in openNewTagSelect"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <el-form-item v-show="form.appSource ==2 " label="应用地址" prop="appAddress" :rules="form.appSource == '2' ? rules.appAddress : [{ required: false }]">
          <el-input v-model.trim="form.appAddress" placeholder="请输入以http://或者https://开头" maxlength="200" show-word-limit class="limit" />
        </el-form-item>
        <el-form-item prop="appSecret" :rules="form.appSource == '2' ? rules.appSecret :rules.appSecret1 ">
          <span slot="label">
            <span class="span-box">
              <el-tooltip class="item" effect="dark" :content="`平台进行集成时的身份令牌。`" placement="top-start">
                <i class="el-icon-question" />
              </el-tooltip>
              应用密钥
            </span>
          </span>
          <el-row :gutter="0">
            <el-col :span="20">
              <el-input v-model.trim="form.appSecret" placeholder="请输入应用密钥" :disabled="form.appId !== null" maxlength="32" show-word-limit class="limit" />
            </el-col>
            <el-col :span="4">
              <el-button :disabled="form.appId !== null" type="primary" style="margin-left: 12px;padding: 10px 34px;" @click="generate()">生成</el-button>
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="排序" prop="appSort">
          <el-input v-model.trim="form.appSort" placeholder="请输入排序" maxlength="8" show-word-limit class="limit" />
        </el-form-item>
        <el-form-item label="应用图标" prop="appIcon" class="icon_class">
          <uploadIcon ref="uploadIcon" v-model="form.appIcon" :file-type="fileType" :file-size="fileSize" :icon-color.sync="form.iconColor" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model.trim="form.remark" :autosize="{minRows: 6, maxRows: 6}" placeholder="请输入描述" maxlength="200" type="textarea" show-word-limit class="limit" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="addLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listApp, getApp, delApp, addApp, updateApp } from "@/api/system/app";
import { uuId } from '@/utils/uuid'
import { isExternal, checkParameterName, checkAppSecret } from '@/utils/validate'
import uploadIcon from './components/uploadIcon.vue'
import appIcon from './components/appIcon.vue'

export default {
  name: "AppAddOrUpdate",
  components: {
    uploadIcon,
    appIcon
  },
  props: {
    watchEdit: {
      type: String,
      default: 'add'
    }
  },
  data() {
    const validateAppSecret = async(rule, value, callback) => {
      if (value.length > 0 && !checkAppSecret(value)) {
        callback(new Error('请输入字母、数字和下划线'))
      } else callback()
    }
    const validateAppCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入应用编码'))
      } else if (!checkParameterName(value)) {
        callback(new Error('应用编码只能输入字母、数字'))
      } else callback()
    }
    return {
      // 遮罩层
      addLoading: false,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        appName: [
          { required: true, message: "应用名称不能为空", trigger: "blur" }
        ],
        appCode: [
          { required: true, message: '应用编码不能为空', trigger: 'blur' },
          { trigger: 'blur', validator: validateAppCode
          }
        ],
        appType: [
          { required: true, message: "应用类型不能为空", trigger: "change" }
        ],
        appIcon: [
          { type: 'array', required: true, trigger: 'change', validator: (rule, value, callback) => {
            const temp = this.form.appIcon
            if (Array.isArray(temp) ? temp.length : temp) {
              callback()
            } else {
              callback(new Error('请上传应用图标'))
            }
          } }
        ],
        appSource: [
          { required: true, message: "应用来源不能为空", trigger: "change" }
        ],
        isSingleIntegration: [
          { required: true, message: "是否单点集成不能为空", trigger: "blur" }
        ],
        isBaseApp: [
          { required: true, message: "是否基础应用不能为空", trigger: "blur" }
        ],
        appSecret: [
          { required: true, message: '应用密钥不能为空', trigger: 'blur' },
          { required: true, validator: validateAppSecret, trigger: 'blur' }
        ],
        appSecret1: [
          { required: false, validator: validateAppSecret, trigger: 'blur' }
        ],
        appAddress: [
          { required: true, trigger: 'change', validator: (rule, value, callback) => {
            if (!this.form.appAddress) {
              callback(new Error('应用地址不能为空'))
            } else if (!isExternal(value)) {
              callback(new Error('应用地址必须以https:// 或者http:// 开头'))
            } else {
              callback()
            }
          }
          }
        ],
        remark: [
          { required: true, trigger: 'blur', validator: (rule, value, callback) => {
            if (!value) {
              callback(new Error('描述不能为空'))
            } else if (value.length < 35) {
              callback(new Error('输入长度至少为35'))
            } else {
              callback()
            }
          } }
        ],
        appSort: [
          { required: true, message: '排序不能为空', trigger: 'blur' },
          { trigger: 'blur', validator: (rule, value, callback) => {
            if (!/^[0-9]*$/.test(value)) {
              callback(new Error('排序格式错误'))
            } else callback()
          }
          }
        ]
      },
      appSourceSelect: [],
      openNewTagSelect: [],
      fileType: [
        'png',
        'jpg',
        'jpeg'
      ],
      fileSize: 0.2,
      appTypeSelect: []
    };
  },
  created() {},
  methods: {
    init(appId) {
      this.title = "添加系统应用";
      this.open = true
      this.appSourceSelect = this.$parent.appSourceSelect
      this.openNewTagSelect = this.$parent.openNewTagSelect
      this.appTypeSelect = this.$parent.deptOptions[0].children
      this.reset();
      if (appId) {
        this.title = "修改系统应用";
        getApp(appId).then(response => {
          const { appIcon, ...res } = response.data
          const temp = res.iconType == 1 ? (appIcon
            ? [{ fileId: appIcon, url: process.env.VUE_APP_BASE_API + appIcon, name: '' }]
            : []) : appIcon
          this.form = {
            ...res,
            appIcon: temp
          }
        });
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        appId: null,
        appName: null,
        appCode: uuId(8),
        appType: null,
        appIcon: null,
        iconType: null,
        iconColor: null,
        activeFlag: 'N',
        statusFlag: 2,
        appSource: 1,
        isSingleIntegration: 1,
        integrationState: null,
        isBaseApp: 1,
        isDefault: 1,
        remark: null,
        appSecret: uuId(32),
        appAddress: '',
        appSort: null,
        delFlag: 'N',
        openNewTag: 1,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const appIcon = this.form.appIcon
          const param = {
            appIcon: Array.isArray(appIcon) ? appIcon[0].fileId : appIcon,
            iconType: Array.isArray(appIcon) ? '1' : '2' // 1自定义图片，2图标
          }
          this.addLoading = true
          let r
          if (this.form.appId != null) {
            r = updateApp({ ...this.form, ...param });
          } else {
            r = addApp({ ...this.form, ...param });
          }
          r.then((res) => {
            this.$modal.msgSuccess("操作成功");
            this.open = false;
            this.$emit('refreshDataList');
          }).finally(()=>{
            this.addLoading = false
          })
        }
      });
    },
    changeAppSource(data) {
      if (data == 2) {
        this.form.openNewTag = 2
      } else {
        this.form.openNewTag = 1
      }
    },
    generate() {
      this.form.appSecret = uuId(32)
    },
  }
};
</script>
